# coding=utf8
import re
import time
import copy
import requests

from friendship_assistant.constants import YouCoffee_Config


class SignIn():
    def __init__(self, error_back=None):
        self.error_back = error_back
        self.headers = {
            "Connection": "keep-alive",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.901.400 QQBrowser/9.0.2524.400",
            # "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4",
        }

    def run(self, logger):
        with open(YouCoffee_Config, encoding="utf8") as fp:
            content = fp.read()

        user_list = re.findall("(\S+)\s*=\s*(\S+)", content)
        for user_li in user_list:
            username = user_li[0]
            usertoken = user_li[1]
            self.signin(username, usertoken)

    def signin(self, username, usertoken):
        sess = requests.Session()

        url = "http://c.youcoffee.com.cn/wx/sign/sign.php?code={}&state=1".format(usertoken)
        headers = copy.deepcopy(self.headers)
        headers.update({
            "Host": "c.youcoffee.com.cn",
        })
        response = sess.get(url, headers=headers)

        print(sess.cookies)
        print(response)
        return

        url = "http://c.youcoffee.com.cn/wx/sign/sign.php?act=sign"
        data = {
            "openid": "orK7HwynDCtYYQxIlnjgu-F27oFk",
            "key": "ebf2c5997c49c39a4ff23b96457f9bde",
            "t": str(int(time.time())),
            "mac": "",
        }
        headers = copy.deepcopy(self.headers)
        headers.update({
            "Host": "c.youcoffee.com.cn",
            # "Referer": "http://c.youcoffee.com.cn/wx/sign/sign.php?code={}&state=1".format(usertoken),
            "Origin": "http://c.youcoffee.com.cn",
        })
        cookies = {}

        response = requests.post(url, data, headers=headers, cookies=cookies).content
        print(response.content)
